from flask import Flask, request
from ToDo.todo_app_with_mysql.manager_mysql import *
manager = TodoManagerWithmysql()

#创建一个服务器程序的实例
app = Flask(__name__)

#Flask处理json时保留原始字符串
app.config["JSON_AS_ASCII"] = False

@app.route("/", methods=['GET'])
def test():
    return "欢迎进入待办事项"

@app.route("/creat", methods=['POST'])
def creat_todo():
    if "title" not in request.form:
        return "参数错误，必须提供 title参数", 400
    else:
        print(request.form)
        todo = manager.create(request.form["title"])
        return todo.__dict__



@app.route("/completed", methods=['GET'])
def mark_completed():
    if "id" not in request.args:
        return "参数错误，必须提供 id参数", 400
    else:
        todo_id = int(request.args['id'])
        todo = manager.mark_completed(todo_id)
        if todo is not None:
            return todo.__dict__
        else:
            return f'todo not found, todo_id={todo_id}', 404


@app.route("/del",  methods=['POST'])
def del_todo():
    if "id" not in request.form:
        return "参数错误，必须提供 id参数", 400
    else:
        return [{"todos": [x.__dict__ for x in manager.del_todo(int(request.form["id"]))]}]


@app.route("/alltodo", methods=["GET"])
def all_todo():
    #已完成事项
    if request.args.get("completed") == "1":
        return {"todos": [x.__dict__ for x in manager.com_todo()]}
    #所有事项
    elif request.args.get("completed") == 'all':
        return {"todos": [x.__dict__ for x in manager.list_todo()]}
    #未完成事项
    else:
        return {"todos": [x.__dict__ for x in manager.not_com()]}


#`app.route()` 装饰器内部调用了 add_url_route 方法
#app.add_url_rule('/completed', view_func=mark_completed)



#flaskapp.py模块执行了自己定义的功能
if __name__ =="__main__":
    app.run()












